package com.mindflow.hbase.tutorials.zookeeper;

import org.apache.zookeeper.*;

import java.util.List;

/**
 * 链接zookeeper
 */
public class ZookeeperCrud {


    public void create() throws KeeperException, InterruptedException {
        ZooKeeper zooKeeper = ZookeeperFactory.getZooKeeper("192.168.216.128:2181");
        String path = "/testGroup";
        String createPath = zooKeeper.create(path,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zooKeeper.close();
    }


    public void update() throws KeeperException, InterruptedException {
        ZooKeeper zooKeeper = ZookeeperFactory.getZooKeeper("192.168.216.128:2181");
        String path = "/testGroup/test2/test21";
        zooKeeper.create(path,null,ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zooKeeper.close();
    }


    public void delete() throws KeeperException, InterruptedException {
        ZooKeeper zooKeeper = ZookeeperFactory.getZooKeeper("192.168.216.128:2181");
        String node = "/testGroup";
        List<String> childrens = zooKeeper.getChildren(node,false);
        for(String children : childrens){
            List list = zooKeeper.getChildren(node.concat("/").concat(children),false);
            if(list.isEmpty()){
                zooKeeper.delete(node.concat("/".concat(children)),-1);
            }else{
            }
        }
        zooKeeper.delete(node,-1);
        zooKeeper.close();
    }

    public void getNode() throws KeeperException, InterruptedException {
        ZooKeeper zooKeeper = ZookeeperFactory.getZooKeeper("192.168.216.128:2181");
        String node = "/testGroup";
        List<String> childrens = zooKeeper.getChildren(node,false);
        if(childrens.isEmpty()){
            System.out.println(node + "children is empty");
            System.exit(1);
        }

        for(String children : childrens){
            System.out.println(children);
        }
        zooKeeper.close();

    }


    public static void main(String[] args) throws KeeperException, InterruptedException {
        ZookeeperCrud zookeeperCrud = new ZookeeperCrud();
//        zookeeperCrud.create();
//        zookeeperCrud.update();
//        zookeeperCrud.getNode();
        zookeeperCrud.delete();
    }

}
